/**
 * 
 */
package wpmp.auth.dao;

import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Component;

import wcommons.beanutils.BeanUtils;
import wpmp.utils.quickbean.User;

/**
 * @author Wayne.Wang<5waynewang@gmail.com>
 * @since 3:25:14 PM Dec 26, 2012
 */
@Component
public class UserDao extends BaseDao {

	private static final String SQL_GET = "SELECT a.user_name,a.login_name,a.password,a.is_admin,a.tel,a.mobile,a.email,a.org_id AS `org.id`,b.name AS `org.name`,b.level AS `org.level` FROM sys_user a,sys_org b WHERE a.org_id=b.id AND login_name=?";

	private static final String SQL_GET_PASSWORD = "SELECT password FROM sys_user WHERE login_name=?";

	private static final String SQL_UPDATE_PASSWORD = "UPDATE sys_user SET password=? WHERE login_name=?";

	public User queryForObject(final String loginName) {
		final SqlRowSet rs = getJdbcTemplate().queryForRowSet(SQL_GET, loginName);
		return rs.next() ? toBean(rs) : null;
	}

	public User toBean(final SqlRowSet rs) {
		final User dest = new User();
		BeanUtils.copySqlRowSetToBean(dest, rs);
		return dest;
	}

	public SqlRowSet queryForRowSet(final String loginName) {
		return getJdbcTemplate().queryForRowSet(SQL_GET, loginName);
	}

	public String getPasswordByLoginName(String loginName) {
		SqlRowSet rs = getJdbcTemplate().queryForRowSet(SQL_GET_PASSWORD, loginName);
		return rs.next() ? rs.getString("password") : null;
	}

	public int updatePassword(String loginName, String pwd) {
		return getJdbcTemplate().update(SQL_UPDATE_PASSWORD, pwd, loginName);
	}
}
